﻿namespace MicroBlog.Infrastructure
{
    /// <summary>
    /// 数据库操作返回对象
    /// </summary>
    public class ContextResult
    {
        private List<ContextError> _errors = new List<ContextError>();

        /// <summary>
        /// 操作是否成功
        /// </summary>
        /// <value>成功为true，其它情况为false</value>
        public bool Succeeded { get; protected set; }
        /// <summary>
        /// 附加的信息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 操作产生的错误信息集合
        /// </summary>
        public IEnumerable<ContextError> Errors => _errors;

        /// <summary>
        /// 返回一个操作成功的对象
        /// </summary>
        public static ContextResult Success { get; } = new ContextResult { Succeeded = true };

        /// <summary>
        /// 创建一个操作失败的对象
        /// </summary>
        /// <param name="errors">错误信息的数据</param>
        /// <returns>一个包含错误信息的数据库操作对象</returns>
        public static ContextResult Failed(params ContextError[] errors)
        {
            var result = new ContextResult { Succeeded = false };
            if (errors != null)
            {
                result._errors.AddRange(errors);
            }
            return result;
        }

        /// <summary>
        /// 成功返回Succeeded，失败返回失败相关的信息
        /// </remarks>
        public override string ToString()
        {
            return Succeeded ?
                   "Succeeded" :
                   string.Format("{0} : {1}", "Failed", string.Join(",", Errors.Select(x => x.Code).ToList()));
        }
    }
}
